package com.talkweb.securitycamera.utils.photocodeclib;

import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVThumbnailUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @version 1.0.1
 * @description: 图片数据生成缩略图
 * @program: Gallery
 * @Author xiaozhijun
 * @Date 2020/12/22 14:43
 */
public class PhotoThumbnail extends IThumbnail {


    @Override
    public PixelMap getThumbPixMap(File f, Size size) {
        //优先使用解码模块获取缩略图
        PixelMap pixelMap = getImageThumb(f, size);
        if (pixelMap == null) {
            //超分辨率的图片解码失败的场景下使用AVThumbnailUtils解码
            boolean isLarge = f.length() > 50 * 1024 * 1024;
            Size autoSize = ThumbPhotoSizeUtils.autoCompressSize(f, size, isLarge);
            if (autoSize == null) {
                autoSize = size;
            }
            pixelMap = AVThumbnailUtils.createImageThumbnail(f, autoSize);
        }
        return pixelMap;
    }

    /**
     * 其他方式获取图片缩略图
     *
     * @param f    图片文件
     * @param size 生成的缩略图大小
     * @return PixelMap 缩略图位图
     */
    private PixelMap getThumbByOtherOption(File f, Size size) {
        InputStream in = null;
        PixelMap pixelMap = null;
        try {
            pixelMap = new PhotoDecode.Builder().desiredSize(size).build().commonDecodePhoto(f.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pixelMap;
    }

    /**
     * 通过Image 通过imageSource.createThumbnailPixelmap获取缩略图
     *
     * @param f    文件
     * @param size 尺寸
     * @return
     */
    public PixelMap getImageThumb(File f, Size size) {
        ImageSource imageSource = null;
        PixelMap pixelMap = null;
        try {
            imageSource = ImageSource.create(f, null);
            Size autoSize = size;
            if (imageSource != null) {
                autoSize = ThumbPhotoSizeUtils.autoCompressSize(imageSource, size);
                if (autoSize == null) {
                    autoSize = size;
                }
            }
            // 将缩略图解码为PixelMap对象
            ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
            decodingOpts.desiredSize = autoSize;

            pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);
        } catch (Exception e) {
            if (imageSource != null) {
                imageSource.release();
            }
        }
        return pixelMap;
    }


}
